package com.itheima.job;

import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.CacheRequest;
import java.util.Set;

@Component
public class RedisToMongoJob {

   @Autowired
   private StringRedisTemplate stringRedisTemplate;

   @Autowired
   private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/1 * * * ?") // 老师用1分钟
    public void movementJob() {
        System.out.println("推荐动态start....");
        //1. 读取redis
        // 1-1 取出跟推荐动态有关的所有key
        Set<String> keys = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");
        // 1-2 遍历
        for (String key : keys) {
            //1-3 获取用户id
            String userIdStr = key.replace("MOVEMENTS_RECOMMEND_", "");
            long userId = Long.parseLong(userIdStr);
            // 1-4 获取推荐给此用户的动态pid
            String pidsStr = stringRedisTemplate.opsForValue().get(key);
            String[] pidArray = pidsStr.split(",");
            //1-5 删除reids中的这个key
            stringRedisTemplate.delete(key);
            //还要删除mongo中推荐给这个用户数据
            mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)),RecommendMovement.class);
            //1-6 遍历pidarray
            for (String pidStr : pidArray) {
                // 1-7转为pid类型
                long pid = Long.parseLong(pidStr);
                //2.同步mongodb
                // 2-1 创建推荐动态实体
                RecommendMovement recommendMovement = new RecommendMovement();
                recommendMovement.setCreated(System.currentTimeMillis());//推荐时间
                recommendMovement.setUserId(userId);//退给谁?
                recommendMovement.setPid(pid);//动态pid
                Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pid)),
                        Movement.class);
                recommendMovement.setPublishId(movement.getId());//动态id
                recommendMovement.setScore(RandomUtil.randomDouble(70,99));
                //2-2 保存实体
                mongoTemplate.save(recommendMovement);
            }
        }
        System.out.println("推荐动态end...");

    }
}
